package Server.Poker.DDZ;

import java.util.HashMap;
import java.util.Map;

public class TimerManager {

	TimerManager() {
		mCallBack = null;
		mCurTime = 0;
	}

	TimerCallBack mCallBack;
	int mCurTime;

	class TimerData {
		int mStartTime;
		int mElapse;
		int mTimerID;
		int mTimerChairID;
		boolean mLoop;

		TimerData() {
			mStartTime = 0;
			mElapse = 0;
			mTimerID = 0;
			mTimerChairID = Constants.INVALID_CHAIR;
			mLoop = false;
		}
	};

	TimerData mGameTimer = new TimerData();
	Map<Integer, TimerData> mTimers = new HashMap<>();

	int SetTimer(int nIDEvent, float nElapse, boolean loop) {
		if (mTimers.containsKey(nIDEvent)) {
			KillTimer(nIDEvent);
		}
		TimerData td = new TimerData();
		td.mStartTime = mCurTime;
		td.mElapse = (int) nElapse * 1000;
		td.mTimerID = nIDEvent;
		td.mLoop = loop;
		mTimers.put(nIDEvent, td);
		return nIDEvent;
	}

	boolean KillTimer(int nIDEvent) {
		if (mTimers.containsKey(nIDEvent)) {
			mTimers.remove(nIDEvent);
			return true;
		}
		return false;
	}

	void SetCallBack(TimerCallBack cb) {
		mCallBack = cb;
	}

	void Update(int frameTime) {
		mCurTime += frameTime;
		// 系统定时器
		Map<Integer, TimerData> temp = mTimers;// 防止在callback里删除定时器引起崩溃
		Integer keys[]  = new Integer[temp.size()];
		keys = temp.keySet().toArray(keys);
		for (int i = 0; i < keys.length; i++) {
			TimerData td  = temp.get(keys[i]);
			if (mCurTime - td.mStartTime >= td.mElapse) {
				if (!td.mLoop) {
					KillTimer(td.mTimerID);
				}
				if (mCallBack != null)
					mCallBack.OnTimer(td.mTimerID);
			}
		}
//		for (Map.Entry<Integer, TimerData> entry : temp.entrySet()) {
//			TimerData td = entry.getValue();
//			if (mCurTime - td.mStartTime >= td.mElapse) {
//				if (!td.mLoop) {
//					KillTimer(td.mTimerID);
//				}
//				if (mCallBack != null)
//					mCallBack.OnTimer(td.mTimerID);
//			}
//		}
		// 游戏定时器
		if (mGameTimer.mTimerID != 0) {
			if (mCurTime - mGameTimer.mStartTime >= 1000) {
				mGameTimer.mStartTime += 1000;
				// 消息处理
				if (mGameTimer.mElapse > 0)
					mGameTimer.mElapse--;
			}
		}
	}
}
